import Tiows from './tiows'
import constant from './constant'
import { ElMessage } from 'element-plus'

export default function () {
  this.imSocketURL = constant.imSocketURL
  this.paramStr = 'Authorization=' + localStorage.getItem('userToken')
  this.binaryType = 'blob'

  // 没有填写聊天室socket url时使用默认的
  if (!this.imSocketURL) {
    let wsProtocol
    const currentProtocol = window.location.protocol
    if (currentProtocol.includes('https')) {
      wsProtocol = 'wss'
    } else {
      wsProtocol = 'ws'
    }
    const ip = window.location.hostname
    const port = window.location.port
    if (!port) {
      this.imSocketURL = wsProtocol + '://' + ip + '/socket'
    } else {
      this.imSocketURL = wsProtocol + '://' + ip + ':' + port + '/socket'
    }
  }

  this.initWs = () => {
    this.tio = new Tiows(this.imSocketURL, this.paramStr, this.binaryType)
    this.tio.connect()
  }

  this.sendMsg = (value) => {
    if (this.tio && this.tio.ws && this.tio.ws.readyState === 1) {
      this.tio.send(value)
      return true
    } else {
      ElMessage({
        message: '发送失败，请重试！',
        type: 'error'
      })
      return false
    }
  }
}
